<?php

class step1SaveAction extends sfAction
{
    public function execute($request)
    {
        if (!$this->getUser()->getPage()->isInstalled())
            $this->installPage($request);

        $this->url_params = LogInstall::log($request, 'step1_save');

        // We need to request the publish_stream permissions *after* adding the tab
        // to the page, or Facebook won't list the page on add.php
        if ($this->getUser()->getAttribute('install_wall_post_enabled'))
            return sfView::SUCCESS;
        else
            $this->redirect('@install_step2?'.$this->url_params);

    }


    private function installPage($request)
    {
        $conn = Doctrine::getTable('Page')->getConnection();
        $conn->beginTransaction();
        try {
            $this->updatePage($request);
            $this->updateFbUser();
            $conn->commit();
        } catch (Exception $e) {
            $conn->rollBack();
            sfContext::getInstance()->getLogger()->err('{Install} Error creating page: '.$e->getMessage());
            throw $e;
        }

        try {
            $this->getUser()->getPage()->State->installMailEvent();
            if ($request->getCookie(sfConfig::get('sf_app').'_sponsoring'))
                $this->saveSponsoringLink($request->getCookie(sfConfig::get('sf_app').'_sponsoring'));
        } catch (Exception $e) {
            sfContext::getInstance()->getLogger()->err('{Install} Error updating page: '.$e->getMessage());
        }
    }


    private function updatePage($request)
    {
        $page = $this->getUser()->getPage();
        if ($request->getParameter('type') === 'app')
            $page->Profile->type = 'app';
        else
            $page->Profile->type = 'page';
		
        $page->updateInfo();

        $page->Profile->culture = $this->getUser()->getCulture();
        $page->Profile->current_api_id = App::getMainApiId();
        $page->Profile->billing_email = $this->getUser()->getFbUser()->email;

        if ($this->getUser()->getFbUser()->is_test_account)
            $page->Profile->is_test = true;

        try{
            $page_admin = new PageAdmin;
            $page_admin->page_id = $page->page_id;
            $page_admin->uid = $this->getUser()->getUid();
            $page_admin->is_admin = true;
            $page_admin->save();
            $page->Admins[] = $page_admin;
        } catch (Exception $e) {
            sfContext::getInstance()->getLogger()->err('{Install} Error Creating PageAdmin: '.$e->getMessage());
        }

        $page->PagePlan->createPlan('trial');
        $page->State->installed_at = date('Y-m-d H:i:s');
        $page->Stats;
        $page->save();
    }


    private function updateFbUser()
    {
        $fb_user = $this->getUser()->getFbUser();
        if ($fb_user) {
            $fb_user->updateInfo();
            $fb_user->save();
        }
    }


    private function saveSponsoringLink($token)
    {
        $sponsoring = Doctrine_Query::create()
            ->from('Sponsoring s')
            ->where('s.token = ?', $token)
            ->fetchOne();

        if (!$sponsoring)
            return;

        $sponsoring_link = Doctrine_Query::create()
            ->from('SponsoringLink sl')
            ->where('sl.godchild_uid = ?', $this->getUser()->getUid())
            ->fetchOne();

        $sponsoring_stat = new SponsoringStats();
        $sponsoring_stat->token = $token;
        $sponsoring_stat->Sponsoring = $sponsoring;
        $sponsoring_stat->is_first = (bool) $sponsoring_link;
        $sponsoring_stat->save();

        if (!$sponsoring_link) {
            $sponsoring_link = new SponsoringLink();
            $sponsoring_link->godchild_uid = $this->getUser()->getUid();
            $sponsoring_link->godfather_uid = $sponsoring->godfather_uid;
            $sponsoring_link->token = $token;
            $sponsoring_link->page_id = $this->getUser()->getPageId();
            $sponsoring_link->save();
        }
    }
}

